package com.app.reportproblem;

import org.json.JSONException;
import org.json.JSONObject;

import com.app.reportproblem.Utils.GetSHA;
import com.app.reportproblem.Utils.PreferenceHelper;
import com.app.reportproblem.httpclient.HttpClientHelper;
import com.app.reportproblem.httpclient.MyJsonHttpResponseHandler;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class AutoLoginActivity extends Activity {
	
	PreferenceHelper preferenceHelper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_auto_login);
		
		preferenceHelper = new PreferenceHelper(this);
		
		initValue();
		
		GetSHA.getSHA(AutoLoginActivity.this);
		
	}
	
	
	void initValue() {
		if (preferenceHelper.getUserId() != 0) {
			gotoMain();
		} else {
			gotoLogin();
		}
		/*if (preferenceHelper.getEmail().equals("") || preferenceHelper.getPass().equals("")) {
			gotoLogin();
		} else {
			login();
		}*/
	}
	
	void gotoLogin() {
		Intent i = new Intent(this, LoginActivity.class);
		finish();
		startActivity(i);
	}
	
	void login(){
		String email = preferenceHelper.getEmail();
		String pass = preferenceHelper.getPass();
		
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
			}

			@Override
			public void onSuccess(JSONObject re) {
				try {
					int status = re.getInt("status");
					switch (status) {
					case 200:
						JSONObject data = re.getJSONObject("data");
						Log.i("DATA", "USERID"+data.toString());
						preferenceHelper.setUserId(data.getInt("userId"));
						preferenceHelper.setName(data.getString("name"));
						preferenceHelper.setMobile(data.getString("mobile"));
						preferenceHelper.setFixed(data.getInt("allowFix"));
						Log.i("DATA", ""+preferenceHelper.getUserId());
						gotoMain();
						break;
					case 400:
						Toast.makeText(AutoLoginActivity.this, getString(R.string.invalid), Toast.LENGTH_SHORT).show();
						break;
					case 404:
						Toast.makeText(AutoLoginActivity.this, getString(R.string.notfound), Toast.LENGTH_SHORT).show();
						break;

					default:
						break;
					}
				} catch (JSONException e) {
					Toast.makeText(AutoLoginActivity.this, getString(R.string.notconnectserver), Toast.LENGTH_SHORT).show();
					e.printStackTrace();
				}
			}
			
		});
		httpClientHelper.login(email, pass);
	}
	
	void gotoMain() {
		finish();
		Intent t = new Intent(AutoLoginActivity.this, MainActivity.class);
		t.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(t);
	}


}
